package com.weiquan.controller;

import com.weiquan.common.Result;
import com.weiquan.service.FileUploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/file")
@Tag(name = "文件管理", description = "文件上传、下载、删除相关接口")
public class FileController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传单个文件
     */
    @PostMapping("/upload")
    @Operation(summary = "上传单个文件", description = "支持图片、文档、音频、视频等多种格式")
    public Result<Map<String, Object>> uploadFile(
            @Parameter(description = "文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "文件分类") @RequestParam(value = "category", defaultValue = "image") String category,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("用户{}上传文件，分类：{}，文件名：{}", userId, category, file.getOriginalFilename());
        
        String fileUrl = fileUploadService.uploadFile(file, category);
        
        Map<String, Object> result = new HashMap<>();
        result.put("url", fileUrl);
        result.put("fileName", file.getOriginalFilename());
        result.put("fileSize", file.getSize());
        result.put("category", category);
        
        return Result.success(result);
    }

    /**
     * 批量上传文件
     */
    @PostMapping("/upload/batch")
    @Operation(summary = "批量上传文件", description = "一次上传多个文件")
    public Result<Map<String, Object>> uploadFiles(
            @Parameter(description = "文件列表") @RequestParam("files") List<MultipartFile> files,
            @Parameter(description = "文件分类") @RequestParam(value = "category", defaultValue = "image") String category,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("用户{}批量上传文件，分类：{}，文件数量：{}", userId, category, files.size());
        
        List<String> fileUrls = fileUploadService.uploadFiles(files, category);
        
        Map<String, Object> result = new HashMap<>();
        result.put("urls", fileUrls);
        result.put("count", fileUrls.size());
        result.put("category", category);
        
        return Result.success(result);
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除文件", description = "根据文件URL删除文件")
    public Result<Void> deleteFile(
            @Parameter(description = "文件URL") @RequestParam String fileUrl,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("用户{}删除文件：{}", userId, fileUrl);
        
        boolean success = fileUploadService.deleteFile(fileUrl);
        
        if (success) {
            return Result.success();
        } else {
            return Result.error("文件删除失败");
        }
    }

    /**
     * 上传头像
     */
    @PostMapping("/upload/avatar")
    @Operation(summary = "上传头像", description = "专门用于上传用户头像")
    public Result<Map<String, Object>> uploadAvatar(
            @Parameter(description = "头像文件") @RequestParam("avatar") MultipartFile avatar,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("用户{}上传头像，文件名：{}", userId, avatar.getOriginalFilename());
        
        // 验证是否为图片文件
        String[] imageTypes = {"image/jpeg", "image/jpg", "image/png", "image/gif"};
        if (!fileUploadService.validateFileType(avatar, imageTypes)) {
            return Result.error("头像只支持JPG、PNG、GIF格式");
        }
        
        // 验证文件大小（头像限制2MB）
        if (!fileUploadService.validateFileSize(avatar, 2 * 1024 * 1024)) {
            return Result.error("头像文件大小不能超过2MB");
        }
        
        String avatarUrl = fileUploadService.uploadFile(avatar, "avatar");
        
        Map<String, Object> result = new HashMap<>();
        result.put("avatarUrl", avatarUrl);
        result.put("fileName", avatar.getOriginalFilename());
        result.put("fileSize", avatar.getSize());
        
        return Result.success(result);
    }

    /**
     * 上传证据文件
     */
    @PostMapping("/upload/evidence")
    @Operation(summary = "上传证据文件", description = "上传维权相关的证据文件")
    public Result<Map<String, Object>> uploadEvidence(
            @Parameter(description = "证据文件") @RequestParam("evidence") MultipartFile evidence,
            @Parameter(description = "证据类型") @RequestParam(value = "evidenceType", defaultValue = "document") String evidenceType,
            @Parameter(description = "证据描述") @RequestParam(value = "description", required = false) String description,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        
        log.info("用户{}上传证据文件，类型：{}，文件名：{}", userId, evidenceType, evidence.getOriginalFilename());
        
        String evidenceUrl = fileUploadService.uploadFile(evidence, "evidence");
        
        Map<String, Object> result = new HashMap<>();
        result.put("evidenceUrl", evidenceUrl);
        result.put("fileName", evidence.getOriginalFilename());
        result.put("fileSize", evidence.getSize());
        result.put("evidenceType", evidenceType);
        result.put("description", description);
        result.put("uploadTime", System.currentTimeMillis());
        
        return Result.success(result);
    }

    /**
     * 获取文件信息
     */
    @GetMapping("/info")
    @Operation(summary = "获取文件信息", description = "根据文件URL获取文件详细信息")
    public Result<Map<String, Object>> getFileInfo(
            @Parameter(description = "文件URL") @RequestParam String fileUrl) {
        
        Map<String, Object> fileInfo = new HashMap<>();
        fileInfo.put("url", fileUrl);
        fileInfo.put("accessible", true); // 这里可以检查文件是否存在
        
        return Result.success(fileInfo);
    }

    /**
     * 获取上传配置
     */
    @GetMapping("/config")
    @Operation(summary = "获取上传配置", description = "获取文件上传的配置信息")
    public Result<Map<String, Object>> getUploadConfig() {
        
        Map<String, Object> config = new HashMap<>();
        config.put("maxFileSize", 10 * 1024 * 1024); // 10MB
        config.put("maxAvatarSize", 2 * 1024 * 1024); // 2MB
        config.put("allowedImageTypes", new String[]{"jpg", "jpeg", "png", "gif", "bmp", "webp"});
        config.put("allowedDocumentTypes", new String[]{"pdf", "doc", "docx", "xls", "xlsx", "txt"});
        config.put("allowedAudioTypes", new String[]{"mp3", "wav", "ogg"});
        config.put("allowedVideoTypes", new String[]{"mp4", "avi", "mov", "wmv"});
        
        return Result.success(config);
    }

    /**
     * 检查文件是否存在
     */
    @GetMapping("/exists")
    @Operation(summary = "检查文件是否存在", description = "检查指定URL的文件是否存在")
    public Result<Map<String, Object>> checkFileExists(
            @Parameter(description = "文件URL") @RequestParam String fileUrl) {
        
        // 这里可以实现文件存在性检查逻辑
        Map<String, Object> result = new HashMap<>();
        result.put("exists", true);
        result.put("url", fileUrl);
        
        return Result.success(result);
    }

    /**
     * 获取文件上传进度（WebSocket或SSE实现）
     */
    @GetMapping("/upload/progress/{taskId}")
    @Operation(summary = "获取上传进度", description = "获取大文件上传的进度信息")
    public Result<Map<String, Object>> getUploadProgress(
            @Parameter(description = "任务ID") @PathVariable String taskId) {
        
        // 这里可以实现上传进度查询逻辑
        Map<String, Object> progress = new HashMap<>();
        progress.put("taskId", taskId);
        progress.put("progress", 100); // 百分比
        progress.put("status", "completed");
        
        return Result.success(progress);
    }
}